<?php
/**
 * 自动刷新跳转脚本
 * @param string $uri
 * @param string $method
 * @param int    $http_code
 */
namespace classlib\core;
function redirect($uri = '/', $method='location', $httpcode=302) {
	switch($method) {
		case 'refresh': header("Refresh:0;url=".$uri);
			break;
		case 'javascript':
			$alert = '';
			if (!is_numeric($httpcode)) {
				$alert = 'alert("'.$httpcode.'");';
			}
			echo <<<ETO_JS
            <script language="javascript">
               {$alert}
                window.top.location.href="{$uri}";
            </script>
ETO_JS;
			break;
		default: 
			header("Location: ".$uri, TRUE, $httpcode);
			break;
	}
	exit;
}

/**
 * 自动装载器配置
 * @param string $class
 * @return null
 */
function auto_loader($class) {
	$file  = COREDIR.'/'.(str_replace('\\', '/', $class)).'.cls.php';
	if (!file_exists($file)) {
		throw new \InvalidArgumentException('You load class script '.$file.' not founds.');
	}
	require $file;
}

/**
 * 生成随机的字符串
 * @param number $len
 * @param number $type
 * @return string
 */
function rand_str($len=32, $type=3) {
	mt_srand(microtime(true) * 100000);
	$str = '';
	switch($type) {
		case 0:
			$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 1:
			$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case 2:
			$str = '0123456789';
			break;
		default:
			$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	}
	$strlen = strlen($str) - 1;
	$sdata  = '';
	for($i=0; $i < $len; $i++) {
		$sdata .= $str[mt_rand(0, $strlen)];
	}
	return $sdata;
}

/**
 * 获取IP数据
 * @return string $ip
 */
function get_ip() {
	static $ip = '';
	if($ip !== '') {
		return $ip;
	}
	if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], 'unknown') != 0) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else if(isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] && strcasecmp($_SERVER['HTTP_CLIENT_IP'], 'unknown') != 0) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} else if(isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	} else {
		$ip = 'Unknown';
	}
	return $ip;
}

/**
 * 截取一个内容指定长度的字符
 * @param string $msg
 * @param int    $len
 * @param string $subfix
 * @param string $charset
 */
function cut_str($msg, $len=15, $subfix='...', $charset='utf-8') {
	$msg    = strip_tags($msg);
	$msg    = mb_substr($msg, 0, $len, $charset);
    $msg   .= $subfix;
	return $msg;
}

/**
 * 出现系统错误退出的时候提示语
 * @param int $code
 */
function do_exit($code) {
	$msg = ($code == 404)? '404 Not Found':'500 Internal Server Error.';
	header('http/1.1 '.$msg);
	header('status: '.$msg);
	exit;
}